package com.yfjin.gl

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.yfjin.gl.camera.Camera2Helper
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {



    private var mCamera2Helper: Camera2Helper? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        checkPermission()

        mCamera2Helper = Camera2Helper(this)
        mCamera2Helper!!.setYUVDataCallback { y, uv, vu, w, h, stride ->
            render_view.setRenderData(y,uv,vu,w,h)
//            i420show(y,uv)
        }
        mCamera2Helper!!.start(null)
//        render_view2.setParams(true, null, 1280, 720, 60)

    }




    fun checkPermission(): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA
                ), 1
            )
        }
        return false
    }


    private var i420: ByteArray? = null
    private fun i420show(y: ByteArray, uv: ByteArray) {
        if (i420 == null) {
            i420 = ByteArray(y.size*3/2)
        }
        System.arraycopy(y, 0, i420, 0, y.size)
        var step=0
        //4:1:1
        val vsizeIndex=y.size+y.size/4
        for (i in y.size..i420!!.size-1) {
            if(i==vsizeIndex){
                step=0
            }
            if (i<vsizeIndex){
                i420!![i]=uv[step*2]
            }else{
                if( (step*2+1)<uv.size){
                    i420!![i]=uv[step*2+1]
                }
            }
            step++
        }
//        render_view2.newDataArrived(i420)
    }
}

